package com.elitedatai.mchtest.manage.service.impl;
import cn.hutool.http.HttpStatus;
import com.dji.sdk.common.HttpResultResponse;
import com.dji.sdk.common.Pagination;
import com.dji.sdk.common.PaginationData;
import com.elitedatai.mchtest.common.model.CustomClaim;
import com.elitedatai.mchtest.common.util.JwtUtil;
import com.elitedatai.mchtest.component.mqtt.config.MqttPropertyConfiguration;
import com.elitedatai.mchtest.manage.model.entity.UserEntity;
import com.elitedatai.mchtest.manage.model.dto.UserDTO;
import com.elitedatai.mchtest.manage.model.dto.UserListDTO;
import com.elitedatai.mchtest.manage.model.dto.WorkspaceDTO;
import com.elitedatai.mchtest.manage.model.enums.UserTypeEnum;
import com.elitedatai.mchtest.manage.repository.UserRepository;
import com.elitedatai.mchtest.manage.service.IUserService;
import com.elitedatai.mchtest.manage.service.IWorkSpaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 用户服务实现类，提供用户相关的业务逻辑处理
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private IWorkSpaceService workSpaceService;

    /**
     * 用户登录验证
     * @param username 用户名
     * @param password 密码
     * @param flag 用户类型标识
     * @return 登录结果响应，包含用户信息和访问令牌
     */
    @Override
    public HttpResultResponse userLogin(String username, String password, Integer flag) {
        UserEntity user = this.getUserByUsername(username);
        if (user == null) {
            return new HttpResultResponse()
                    .setCode(HttpStatus.HTTP_UNAUTHORIZED)
                    .setMessage("用户名错误");
        }
        if(flag.intValue()!=user.getUserType().intValue()){
            return HttpResultResponse.error(HttpStatus.HTTP_UNAUTHORIZED,"用户类型错误");
        }
        if (!password.equals(user.getPassword())) {
            return new HttpResultResponse()
                    .setCode(HttpStatus.HTTP_UNAUTHORIZED)
                    .setMessage("密码错误");
        }
        Optional<WorkspaceDTO> workspaceDTO = workSpaceService.getWorkspaceByWorkspaceId(user.getWorkspaceId());
        System.out.println("获取工作空间根据工作空间id："+workspaceDTO);
        if(workspaceDTO.isEmpty()){
            return HttpResultResponse.error(HttpStatus.HTTP_UNAUTHORIZED,"工作空间不存在");
        }
        CustomClaim customClaim = new CustomClaim(user.getUserId(),user.getUsername(),user.getUserType(),workspaceDTO.get().getWorkspaceId());

        // 生成token
        String token = JwtUtil.createToken(customClaim.convertToMap());

        UserDTO userDTO = entityConvertToDTO(user);
        userDTO.setAccessToken(token);
        userDTO.setWorkspaceId(workspaceDTO.get().getWorkspaceId());
        return HttpResultResponse.success(userDTO);
    }

    /**
     * 根据用户名获取用户信息
     * @param username 用户名
     * @param workspaceId 工作空间ID
     * @return 用户信息响应
     */
    @Override
    public HttpResultResponse getUserByUsername(String username, String workspaceId) {
        UserEntity userEntity = this.getUserByUsername(username);
        if (userEntity == null) {
            return new HttpResultResponse()
                    .setCode(org.springframework.http.HttpStatus.UNAUTHORIZED.value())
                    .setMessage("用户不存在");
        }

        UserDTO user = this.entityConvertToDTO(userEntity);
        user.setWorkspaceId(workspaceId);

        return HttpResultResponse.success(user);
    }

    /**
     * 根据工作空间ID分页获取用户列表
     * @param page 页码（从0开始）
     * @param pageSize 每页大小
     * @param workspaceId 工作空间ID
     * @return 分页用户列表数据
     */
    @Override
    public PaginationData<UserListDTO> getUsersByWorkspaceId(long page, long pageSize, String workspaceId) {
        Page<UserEntity> userEntityPage = userRepository.findByWorkspaceId(workspaceId, PageRequest.of((int) page-1, (int) pageSize));

        List<UserListDTO> usersList = userEntityPage.getContent()
                .stream()
                .map(this::entity2UserListDTO)
                .collect(Collectors.toList());
        return new PaginationData<>(usersList, new Pagination(userEntityPage.getNumber()+1, userEntityPage.getSize(), userEntityPage.getTotalElements()));

    }

    /**
     * 更新用户信息
     * @param workspaceId 工作空间ID
     * @param userId 用户ID
     * @param user 用户信息
     * @return 更新结果
     */
    @Override
    public Boolean updateUser(String workspaceId, String userId, UserListDTO user) {
        return null;
    }

    /**
     * 刷新用户token
     * @param token 原始token
     * @return 用户DTO可选包装
     */
    @Override
    public Optional<UserDTO> refreshToken(String token) {
        return Optional.empty();
    }

    /**
     * 根据用户名获取用户实体
     * @param username 用户名
     * @return 用户实体对象
     */
    private UserEntity getUserByUsername(String username) {
        return userRepository.findByUsername(username);
    }


    /**
     * 将用户实体转换为用户列表DTO
     * @param entity 用户实体对象
     * @return 用户列表DTO对象
     */
    private UserListDTO entity2UserListDTO(UserEntity entity) {
        UserListDTO.UserListDTOBuilder builder = UserListDTO.builder();
        if (entity != null) {
            builder.userId(entity.getUserId())
                    .username(entity.getUsername())
                    .mqttUsername(entity.getMqttUsername())
                    .mqttPassword(entity.getMqttPassword())
                    .userType(UserTypeEnum.find(entity.getUserType()).getDesc())
                    .createTime(LocalDateTime.ofInstant(
                            Instant.ofEpochMilli(entity.getCreateTime()), ZoneId.systemDefault()));
            Optional<WorkspaceDTO> workspaceOpt = workSpaceService.getWorkspaceByWorkspaceId(entity.getWorkspaceId());
            workspaceOpt.ifPresent(workspace -> builder.workspaceName(workspace.getWorkspaceName()));
        }

        return builder.build();
    }

    /**
     * 将数据库实体对象转换为用户数据传输对象
     * @param entity 用户实体对象
     * @return 用户DTO对象
     */
    private UserDTO entityConvertToDTO(UserEntity entity) {
        if (entity == null) {
            return null;
        }
        return UserDTO.builder()
                .userId(entity.getUserId())
                .username(entity.getUsername())
                .userType(entity.getUserType())
                .mqttUsername(entity.getMqttUsername())
                .mqttPassword(entity.getMqttPassword())
                .mqttAddr(MqttPropertyConfiguration.getBasicMqttAddress())
                .build();
    }

}